package com.tengju.payment.infrastructure.shared;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.methods.StringRequestEntity;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.io.IOUtils;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

@Slf4j
public class HttpClientUtil {

    /**
     * HTTP的Post请求方式
     * @param strUrl 访问地址
     * @param param 参数字符串
     * */
    public static String doPost(String strUrl, String param) {
        String returnStr = null; // 返回结果定义
        URL url = null;
        HttpURLConnection httpURLConnection = null;

        try {
            url = new URL(strUrl);
            httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
            httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setRequestMethod("POST"); // post方式
            httpURLConnection.connect();
            //POST方法时使用
            byte[] byteParam = param.getBytes("UTF-8");
            DataOutputStream out = new DataOutputStream(httpURLConnection.getOutputStream());
            out.write(byteParam);
            out.flush();
            out.close();
            BufferedReader reader = new BufferedReader(
                    new InputStreamReader(httpURLConnection.getInputStream(), "utf-8"));
            StringBuffer buffer = new StringBuffer();
            String line = "";
            while ((line = reader.readLine()) != null) {
                buffer.append(line);
            }

            reader.close();
            returnStr = buffer.toString();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            if (httpURLConnection != null) {
                httpURLConnection.disconnect();
            }
        }
        return returnStr;
    }

    //将map型转为请求参数型
    public static String urlencode(Map<String, Object> data) {
        StringBuilder apistore = new StringBuilder();
        for (Map.Entry i : data.entrySet()) {
            try {
                apistore.append(i.getKey()).append("=").append(
                        URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        return apistore.toString();
    }



    public static byte[] post(String url, String data) {
        PostMethod postMethod = null;
        try {
            HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
            httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            postMethod = new PostMethod(url);
            postMethod.setRequestHeader("Content-Type", "text/xml; charset=UTF-8");
            postMethod.setRequestEntity(new StringRequestEntity(data, "text/html", "UTF-8"));
            // 执行postMethod
            httpClient.executeMethod(postMethod);
            // 读取内容
            InputStream resInputStream = null;
            resInputStream = postMethod.getResponseBodyAsStream();
            byte[] resByteArray = IOUtils.toByteArray(resInputStream);
            return resByteArray;
        } catch (Exception ex) {
            return null;
        } finally {
            try {
                if (postMethod != null && !postMethod.isAborted()) {
                    postMethod.releaseConnection();
                }
            } catch (Exception e2) {
            }

        }
    }


    public static String post(String url, NameValuePair[] data) {
        PostMethod postMethod = null;
        try {
            HttpClient httpClient = new HttpClient(new HttpClientParams(), new SimpleHttpConnectionManager(true));
            httpClient.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
            postMethod = new PostMethod(url);
            // 将表单的值放入postMethod中
            postMethod.setRequestBody(data);
            // 执行postMethod
            httpClient.executeMethod(postMethod);
            // 读取内容
            InputStream resInputStream = null;
            resInputStream = postMethod.getResponseBodyAsStream();
            // 处理内容
            BufferedReader reader = new BufferedReader(new InputStreamReader(resInputStream));
            String tempBf = null;
            StringBuffer html = new StringBuffer();
            while ((tempBf = reader.readLine()) != null) {
                html.append(tempBf);
            }

            String resMessage = html.toString();
            return resMessage;
        } catch (Exception ex) {
            log.error("post请求异常", ex);
            return null;
        } finally {
            try {
                if (postMethod != null && !postMethod.isAborted()) {
                    postMethod.releaseConnection();
                }
            } catch (Exception e2) {
                log.warn("关闭连接失败", e2);
            }

        }
    }
}
